import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * @ClassName LC12
 * 整数转罗马数字
 * @Author ykx
 * @Date 2024/3/3 21:48
 * @Version 1.0
 */
public class LC12 {

    public static void main(String[] args) {
        int i = 465;
        System.out.println(i +
                "转换成罗马字符是:" + intToRoman(i));
    }

    public static String intToRoman(int num) {
        // 两个字母的罗马数字
        Map<Integer, String> specialMap = new HashMap<>();

        specialMap.put(4, "IV");
        specialMap.put(9, "IX");
        specialMap.put(40, "XL");
        specialMap.put(90, "XC");
        specialMap.put(400, "CD");
        specialMap.put(900, "CM");

        // 再处理单字母
        Map<Integer, Character> map = new TreeMap<>((o1, o2) -> o2 - o1);
        map.put(1, 'I');
        map.put(5, 'V');
        map.put(10, 'X');
        map.put(50, 'L');
        map.put(100, 'C');
        map.put(500, 'D');
        map.put(1000, 'M');

        StringBuilder result = new StringBuilder();

        int i = 1;

        while (num != 0) {
            int bit = (int) (num % Math.pow(10, i));
            num = num - bit;
            if (specialMap.get(bit) != null) {
                result.insert(0, specialMap.get(bit));
            } else {
                String s = "";
                while (bit != 0) {
                    Integer maxKey = getMaxKey(map, bit);
                    s = s + map.get(maxKey);
                    bit -= maxKey;
                }
                result.insert(0, s);
            }
            i++;
        }

        return result.toString();
    }

    public static Integer getMaxKey(Map<Integer, Character> map, int bit) {
        Iterator<Map.Entry<Integer, Character>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, Character> entry = iterator.next();
            if (entry.getKey() <= bit) {
                return entry.getKey();
            }
        }
        return 0;
    }

}
